<script lang="ts">
export default {
  name: "xt-wang-editor",
};
</script>

<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import Typings from "../../../typings";

interface Props {
  modelValue: string;
  height?: string;
  mode?: "default" | "simple";
  toolbarConfig?: Object;
  editorConfig?: Object;
  isHtml?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: "",
  height: "400px",
  mode: "default",
  toolbarConfig: () => ({}), // 工具栏配置
  editorConfig: () => ({}), // 编辑栏配置
  isHtml: false, // 是否以 v-html 的形式展示
});

const defaultEditorConfig = {
  placeholder: "请输入内容...",
  maxLength: 2000,
  MENU_CONF: {
    // 上传图片配置
    uploadImage: {
      server: "/file/editor-upload",
      fieldName: "file",
      timeout: 60 * 1000, // 60s
    },
  },
};

// 回调钩子
const emit = defineEmits(["update:modelValue", "created", "change"]);

// 编辑器实例，必须用 shallowRef
// 组件销毁时，要及时销毁编辑器
const editorRef = shallowRef<Typings.Editor.IDomEditor>();

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 创建成功
const onCreated = (editor: Typings.Editor.IDomEditor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  emit("created", editorRef.value);
};

// 编辑器内容
const htmlValue = ref<string>(props.modelValue);

const onChange = (editor: Typings.Editor.IDomEditor) => {
  emit("change", editor);
  // 更新外部的内容
  emit("update:modelValue", editor.getHtml());
};
</script>

<template>
  <div class="xt-wang-editor" v-if="!isHtml">
    <Toolbar
      class="toolbar-container"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      class="editor-container"
      v-model="htmlValue"
      v-bind="$attrs"
      :mode="mode"
      :style="{
        height,
      }"
      :defaultConfig="{ ...defaultEditorConfig, ...editorConfig }"
      @onChange="onChange"
      @onCreated="onCreated"
    />
  </div>

  <!-- v-html 的形式展示 -->
  <xt-scrollbar v-else class="xt-wang-editor-html" :height="height">
    <div v-html="htmlValue" />
  </xt-scrollbar>
</template>

<style lang="scss">
@use "../../../scss/xt-wang-editor.scss";
</style>
